package com.example.demo.thread.singleton;

/**
 * @Description: volatile实现单例模式
 * @Author: LLL
 * @Date: 2020-03-18 12:58
 **/
public class SingletonInstance {

    private static /*volatile*/ SingletonInstance instance = null;

    private SingletonInstance() {
        System.out.println(Thread.currentThread().getName() + "\t我是构造方法SingletonInstance()");
    }

    // 加synchronized可以解决多线程问题
    //    public static synchronized SingletonInstance getInstance() {
    //        if (instance == null) {
    //            instance = new SingletonInstance();
    //        }
    //        return instance;
    //    }
    /*
     * Description: DCL双重锁检查机制实现单例模式
     * @param
     * @return: com.example.demo.thread.singleton.SingletonInstance
     * @author: liull
     * @date: 2020/3/18 13:15
     */
    public static SingletonInstance getInstance() {
        if (instance == null) {
            synchronized (SingletonInstance.class) {
                if (instance == null) {
                    instance = new SingletonInstance();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        //        System.out.println(SingletonInstance.getInstance() == SingletonInstance.getInstance());
        //        System.out.println(SingletonInstance.getInstance() == SingletonInstance.getInstance());
        //        System.out.println(SingletonInstance.getInstance() == SingletonInstance.getInstance());
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> SingletonInstance.getInstance()).start();
        }
    }
}
